//
//  CustomTextField.swift
//  Eternity
//
//  Created by cll12_12 on 2016/12/28.
//  Copyright © 2016年 ZhengWei. All rights reserved.
//

import UIKit

enum LOGINORGETCODE {
    case LOGIN
    case GETCODE
}

protocol CustomTextFieldDelegate: NSObjectProtocol {
    func resendAction(sender: UIButton)
}

class CustomTextField: UITextField {

    var myDelegate: CustomTextFieldDelegate!
    
    // MARK: - life cycle
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        createUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - event response
    func resendAction(sender: UIButton) {
        if self.myDelegate.responds(to: #selector(CustomTextField.resendAction(sender:))) {
            self.myDelegate.resendAction(sender: sender)
        }
    }
    
    // MARK: - private method
    func initBaseLayout() {
    }
    
    func layoutPageSubviews() {
    }
    
    func createUI() {
        self.backgroundColor = UIColor.white
        self.layer.borderWidth = 0.5
        self.layer.borderColor = UIColor(hexString: "#D1D1D1")?.cgColor
        self.leftView = leftLabel
        self.leftViewMode = .always
        self.rightView = rightBtn
        self.font = UIFont(name: "PingFangSC-Regular", size: 15)
    }
    
    func configUI(type: LOGINORGETCODE) {
        if type == .GETCODE {
            leftLabel.text = "  手机号码"
            self.clearsOnBeginEditing = true
            self.clearButtonMode = .whileEditing
            self.placeholder = "请输入手机号码"
            self.keyboardType = .phonePad
        } else if type == .LOGIN {
            self.rightViewMode = .always
            rightBtn.setTitle("59秒后重发", for: .normal)
            leftLabel.text = "  验证码"
            self.placeholder = "请输入验证码"
            self.keyboardType = .numberPad
        }
    }
    
    // MARK: - setters and getters
    var _leftLabel: UILabel!
    var leftLabel: UILabel {
        if _leftLabel == nil {
            _leftLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 84, height: 15))
            _leftLabel.font = UIFont(name: "PingFangSC-Regular", size: 15)
            _leftLabel.textColor = UIColor(hexString: "#252525")
            
        }
        return _leftLabel
    }
    
    var _rightBtn: UIButton!
    var rightBtn: UIButton {
        if _rightBtn == nil {
            _rightBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 88, height: 15))
            _rightBtn.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 14)
            _rightBtn.setTitleColor(UIColor(hexString: "#CCCCCC"), for: .normal)
            _rightBtn.isEnabled = false
            _rightBtn.addTarget(self, action: #selector(CustomTextField.resendAction(sender:)), for: .touchUpInside)
        }
        return _rightBtn
    }
}
